/**
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * This file is a part of the CANN Open Software.
 * Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */

/**
 * @file main.cpp
 */
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <vector>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>
#include <fcntl.h>

#include "acl/acl.h"
#include "aclnn_mla.h"

#define SUCCESS 0
#define FAILED 1

#define INFO_LOG(fmt, args...) fprintf(stdout, "[INFO]  " fmt "\n", ##args)
#define WARN_LOG(fmt, args...) fprintf(stdout, "[WARN]  " fmt "\n", ##args)
#define ERROR_LOG(fmt, args...) fprintf(stderr, "[ERROR]  " fmt "\n", ##args)

#define CHECK_RET(cond, return_expr) \
    do {                             \
        if (!(cond)) {               \
            return_expr;             \
        }                            \
    } while (0)

#define LOG_PRINT(message, ...)         \
    do {                                \
        printf(message, ##__VA_ARGS__); \
    } while (0)

bool ReadFile(const std::string &filePath, size_t fileSize, void *buffer, size_t bufferSize)
{
    struct stat sBuf;
    int fileStatus = stat(filePath.data(), &sBuf);
    if (fileStatus == -1) {
        ERROR_LOG("failed to get file %s", filePath.c_str());
        return false;
    }
    if (S_ISREG(sBuf.st_mode) == 0) {
        ERROR_LOG("%s is not a file, please enter a file", filePath.c_str());
        return false;
    }

    std::ifstream file;
    file.open(filePath, std::ios::binary);
    if (!file.is_open()) {
        ERROR_LOG("Open file failed. path = %s", filePath.c_str());
        return false;
    }

    std::filebuf *buf = file.rdbuf();
    size_t size = buf->pubseekoff(0, std::ios::end, std::ios::in);
    if (size == 0) {
        ERROR_LOG("file size is 0");
        file.close();
        return false;
    }
    if (size > bufferSize) {
        ERROR_LOG("file size is larger than buffer size");
        file.close();
        return false;
    }
    buf->pubseekpos(0, std::ios::in);
    buf->sgetn(static_cast<char *>(buffer), size);
    fileSize = size;
    file.close();
    return true;
}

bool WriteFile(const std::string &filePath, const void *buffer, size_t size)
{
    if (buffer == nullptr) {
        ERROR_LOG("Write file failed. buffer is nullptr");
        return false;
    }

    int fd = open(filePath.c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWRITE);
    if (fd < 0) {
        ERROR_LOG("Open file failed. path = %s", filePath.c_str());
        return false;
    }

    auto writeSize = write(fd, buffer, size);
    (void) close(fd);
    if (writeSize != size) {
        ERROR_LOG("Write file Failed.");
        return false;
    }

    return true;
}

int64_t GetShapeSize(const std::vector<int64_t> &shape)
{
    int64_t shapeSize = 1;
    for (auto i : shape) {
        shapeSize *= i;
    }
    return shapeSize;
}

int Init(int32_t deviceId, aclrtStream *stream)
{
    // 固定写法，acl初始化
    auto ret = aclInit(nullptr);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return FAILED);
    ret = aclrtSetDevice(deviceId);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return FAILED);
    ret = aclrtCreateStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return FAILED);

    return SUCCESS;
}

template <typename T>
int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr,
                    aclDataType dataType, aclTensor **tensor)
{
    auto size = GetShapeSize(shape) * sizeof(T);
    // 调用aclrtMalloc申请device侧内存
    auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return FAILED);

    // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return FAILED);

    // 调用aclCreateTensor接口创建aclTensor
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND, shape.data(),
                            shape.size(), *deviceAddr);
    return SUCCESS;
}

int main(int argc, char **argv)
{
    // 1. （固定写法）device/stream初始化, 参考acl对外接口列表
    // 根据自己的实际device填写deviceId
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return FAILED);

    // 2. 构造输入与输出，需要根据API的接口自定义构造
    std::vector<int64_t> qSeqLen = {};
    std::vector<int64_t> contextLens = {256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256};
    // std::vector<float> coors_range = {1.1, 1.3, 1.4, 98.4, 87.6, 103.7};
    // int32_t max_points = 5;
    // bool reverse_index = false;
    // int32_t max_voxels = 500;
    // aclFloatArray* voxel_sizeAcl = aclCreateFloatArray(voxel_size.data(), voxel_size.size());
    // aclFloatArray* coors_rangeAcl = aclCreateFloatArray(coors_range.data(), coors_range.size());
    int type = 0;
    int headSize = 32;
    float tor = 0.041666666666666664;
    int kvHead = 1;
    int maskType = 0;
    int cacheMode = 1;
    aclIntArray* contextLensAcl = aclCreateIntArray(contextLens.data(), contextLens.size());
    aclIntArray* qSeqLenAcl = aclCreateIntArray(qSeqLen.data(), qSeqLen.size());
    std::vector<int64_t> inputQueryShape = {32, 32, 512};
    std::vector<int64_t> inputQueryRopeShape = {32, 32, 64};
    std::vector<int64_t> inputkvCacheShape = {64, 128, 1, 512};
    std::vector<int64_t> inputkvCacheRopeShape = {64, 128, 1, 64};
    std::vector<int64_t> inputblock_tablesShape = {32, 2};
    std::vector<int64_t> inputcontextLensShape = {32};
    std::vector<int64_t> outputShape = {32, 32, 512};
    void *inputQueryDeviceAddr = nullptr;
    void *inputQueryRopeDeviceAddr = nullptr;
    void *inputkvCacheDeviceAddr = nullptr;
    void *inputkvCacheRopeDeviceAddr = nullptr;
    void *inputblock_tablesDeviceAddr = nullptr;
    void *inputcontextLensDeviceAddr = nullptr;
    void *outputDeviceAddr = nullptr;
    aclTensor *inputQuery = nullptr;
    aclTensor *inputQueryRope = nullptr;
    aclTensor *inputkvCache = nullptr;
    aclTensor *inputkvCacheRope = nullptr;
    aclTensor *inputblock_tables = nullptr;
    aclTensor *inputcontextLens = nullptr;
    aclTensor *output = nullptr;
    size_t inputQueryShapeSize_1 = inputQueryShape[0] * inputQueryShape[1] * inputQueryShape[2];
    size_t inputQueryRopeShapeSize_1 = inputQueryRopeShape[0] * inputQueryRopeShape[1] * inputQueryRopeShape[2];
    size_t inputkvCacheShapeSize_1 = inputkvCacheShape[0] * inputkvCacheShape[1] * inputkvCacheShape[2] * inputkvCacheShape[3];
    size_t inputkvCacheRopeShapeSize_1 = inputkvCacheRopeShape[0] * inputkvCacheRopeShape[1] * inputkvCacheRopeShape[2] * inputkvCacheRopeShape[3];
    size_t inputblock_tablesShapeSize_1 = inputblock_tablesShape[0] * inputblock_tablesShape[1];
    size_t inputcontextLensShapeSize_1 = inputcontextLensShape[0];
    size_t outputShapeSize_1 = outputShape[0] * outputShape[1] * outputShape[2];
    size_t dataType = 2;
    size_t dataType4 = 4;
    std::vector<aclFloat16> inputQueryHostData(inputQueryShapeSize_1);
    std::vector<aclFloat16> inputQueryRopeHostData(inputQueryRopeShapeSize_1);
    std::vector<aclFloat16> inputkvCacheHostData(inputkvCacheShapeSize_1);
    std::vector<aclFloat16> inputkvCacheRopeHostData(inputkvCacheRopeShapeSize_1);
    std::vector<int32_t> inputblock_tablesHostData(inputblock_tablesShapeSize_1);
    std::vector<int32_t> inputcontextLensHostData(inputcontextLensShapeSize_1);
    std::vector<aclFloat16> outputHostData(outputShapeSize_1);

    size_t fileSize = 0;
    void** input1 = (void**)(&inputQueryHostData);
    void** input2 = (void**)(&inputQueryRopeHostData);
    void** input3 = (void**)(&inputkvCacheHostData);
    void** input4 = (void**)(&inputkvCacheRopeHostData);
    void** input5 = (void**)(&inputblock_tablesHostData);
    void** input6 = (void**)(&inputcontextLensHostData);

    //读取数据
    ReadFile("../input/input_query.bin", fileSize, *input1, inputQueryShapeSize_1 * dataType);
    ReadFile("../input/input_queryRope.bin", fileSize, *input2, inputQueryRopeShapeSize_1 * dataType);
    ReadFile("../input/input_kvCache.bin", fileSize, *input3, inputkvCacheShapeSize_1 * dataType);
    ReadFile("../input/input_kvCacheRope.bin", fileSize, *input4, inputkvCacheRopeShapeSize_1 * dataType);
    ReadFile("../input/input_block_tables.bin", fileSize, *input5, inputblock_tablesShapeSize_1 * dataType4);
    ReadFile("../input/input_contextLens.bin", fileSize, *input6, inputcontextLensShapeSize_1 * dataType4);

    INFO_LOG("Set input success");
    // 创建input aclTensor
    ret = CreateAclTensor(inputQueryHostData, inputQueryShape, &inputQueryDeviceAddr, aclDataType::ACL_FLOAT16, &inputQuery);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    ret = CreateAclTensor(inputQueryRopeHostData, inputQueryRopeShape, &inputQueryRopeDeviceAddr, aclDataType::ACL_FLOAT16, &inputQueryRope);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    ret = CreateAclTensor(inputkvCacheHostData, inputkvCacheShape, &inputkvCacheDeviceAddr, aclDataType::ACL_FLOAT16, &inputkvCache);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED); 
    ret = CreateAclTensor(inputkvCacheRopeHostData, inputkvCacheRopeShape, &inputkvCacheRopeDeviceAddr, aclDataType::ACL_FLOAT16, &inputkvCacheRope);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    ret = CreateAclTensor(inputblock_tablesHostData, inputblock_tablesShape, &inputblock_tablesDeviceAddr, aclDataType::ACL_INT32, &inputblock_tables);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    ret = CreateAclTensor(inputcontextLensHostData, inputcontextLensShape, &inputcontextLensDeviceAddr, aclDataType::ACL_INT32, &inputcontextLens);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);                   
   
    // 创建output aclTensor
    ret = CreateAclTensor(outputHostData, outputShape, &outputDeviceAddr, aclDataType::ACL_FLOAT16, &output);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    INFO_LOG("create tensor success");    
    // 3. 调用CANN自定义算子库API

    uint64_t workspaceSize = 0;
    aclOpExecutor *executor;
    // 计算workspace大小并申请内存
    ret = aclnnMLAGetWorkspaceSize(inputQuery, inputQueryRope, inputkvCache, inputkvCacheRope, inputblock_tables, inputcontextLens,
                                             nullptr, nullptr, nullptr, nullptr,
                                             type, headSize, tor, kvHead, 0, maskType, 0, nullptr, contextLensAcl, 0, cacheMode, 
                                             output, nullptr, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMLAGetWorkspaceSize failed. ERROR: %d\n", ret); return FAILED);
    void *workspaceAddr = nullptr;
    if (workspaceSize > 0) {
        ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return FAILED;);
    }
    INFO_LOG("Get workspace success"); 
    // 执行算子
    ret = aclnnMLA(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMLA failed. ERROR: %d\n", ret); return FAILED);
    INFO_LOG("execute operator success"); 
    // 4. （固定写法）同步等待任务执行结束
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return FAILED);

    // 5. 获取输出的值，将device侧内存上的结果拷贝至host侧，需要根据具体API的接口定义修改
    auto size1 = GetShapeSize(outputShape);
    std::vector<aclFloat16> resultData1(size1, 0);
    ret = aclrtMemcpy(resultData1.data(), resultData1.size() * sizeof(resultData1[0]), outputDeviceAddr,
                    size1 * sizeof(aclFloat16), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return FAILED);
    void** output1 = (void**)(&resultData1);
    //写出数据
    WriteFile("../output/output_attenOut.bin", *output1, outputShapeSize_1 * dataType);
    INFO_LOG("Write output1 success");


    // 6. 释放aclTensor，需要根据具体API的接口定义修改
    aclDestroyTensor(inputQuery);
    aclDestroyTensor(inputQueryRope);
    aclDestroyTensor(inputkvCache);
    aclDestroyTensor(inputkvCacheRope);
    aclDestroyTensor(inputblock_tables);
    aclDestroyTensor(inputcontextLens);
    aclDestroyTensor(output);

    // 7. 释放device资源，需要根据具体API的接口定义修改
    aclrtFree(inputQueryDeviceAddr);
    aclrtFree(inputQueryRopeDeviceAddr);
    aclrtFree(inputkvCacheDeviceAddr);
    aclrtFree(inputkvCacheRopeDeviceAddr);
    aclrtFree(inputblock_tablesDeviceAddr);
    aclrtFree(inputcontextLensDeviceAddr);
    aclrtFree(outputDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();

    return SUCCESS;
}
